package com.sgu6.sgu6_machine.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.sgu6.sgu6_machine.common.Constant;
import com.sgu6.sgu6_machine.config.MachineConfig;
import com.sgu6.sgu6_machine.container.MachineContainer;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class HttpUtils {

    private static String TAG = HttpUtils.class.getCanonicalName();
    private static String ROOT_PATH = Environment.getExternalStorageDirectory().getPath();
    private static String UPLOAD_PATH = ROOT_PATH + "/sgu6/logs/";

    public static void uploadLogFile(final Context context, String machineNo, String name) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dff.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        String ee = dff.format(new Date());
//        String fileName = machineNo+"-"+new Date().toLocaleString().replace(" ","").replace("年","-").replace("月","-").replace("日","-").replace(":","-");
        String fileName = machineNo + "-" + ee;
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "******";
        try {
            URL url;
            if (MachineContainer.machineConfigDto.isBeta) {
                url = new URL(Constant.LOG_UPLOAD_BETA);
            } else {
                url = new URL(Constant.LOG_UPLOAD_DEV);
            }
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + ".txt\"" + end);
//          dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
//                  + uploadFilePath.substring(uploadFilePath.lastIndexOf("/") + 1) + "\"" + end);
            dos.writeBytes(end);
            // 文件通过输入流读到Java代码中-++++++++++++++++++++++++++++++`````````````````````````
            FileInputStream fis = new FileInputStream(UPLOAD_PATH + name);
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            while ((count = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, count);

            }
            fis.close();
            Log.i(TAG, "uploadLogFile: file send to server............");
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
            dos.flush();

            // 读取服务器返回结果
            InputStream is = httpURLConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String result = br.readLine();
            ((Activity) context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "文件上传成功", Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "uploadLogFile: file upload succeed！");
                }
            });
            dos.close();
            is.close();

        } catch (Exception e) {
            e.printStackTrace();
            Log.i(TAG, "uploadLogFile: " + e.getLocalizedMessage());
            ((Activity) context).runOnUiThread(() -> Toast.makeText(context, "文件上传失败，请重试", Toast.LENGTH_SHORT).show());
        }
    }

}
